package cn.onein.edu.web.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import cn.onein.edu.biz.bean.Order;
import cn.onein.edu.biz.bean.Product;
import cn.onein.edu.biz.bean.User;
import cn.onein.edu.common.ProductType;
import cn.onein.edu.common.SexType;
import cn.onein.edu.util.DateUtil;
import cn.onein.edu.util.StringUtil;
import cn.onein.edu.web.common.base.BaseController;
import cn.onein.edu.web.service.PaymentService;
import cn.onein.edu.web.service.UserService;
import cn.onein.edu.web.vo.OrderVO;
import cn.onein.edu.web.vo.ProductVO;

/**
 * 注册 控制器
 * 
 * @author Justin
 * 
 */
@Controller
public class RegisterController extends BaseController {

	Logger logger = Logger.getLogger(RegisterController.class);

	@Autowired
	private UserService userService;
	
	@Autowired
	private PaymentService paymentService;

	/**
	 * 注册首页
	 * 
	 * @return
	 */
	@RequestMapping(value = "/register", method = { RequestMethod.GET,
			RequestMethod.POST })
	public ModelAndView index(HttpServletResponse resp, HttpServletRequest req)
			throws Exception {
		ModelAndView model = new ModelAndView("register/reg1");
		
		model.addObject("email", req.getParameter("email"));
		model.addObject("birthdaytemp", req.getParameter("birthdaytemp"));
		String sextemp = req.getParameter("sex");
		model.addObject("sextemp", sextemp == null ? "1" : sextemp);
		
		this.setMenu(model, BaseController.MENU_VALUE_REGISTER);
		return model;
	}

	/**
	 * 验证邮箱是否存在
	 * 
	 * @return
	 */
	@RequestMapping(value = "/register/validateEmail.json", method = {
			RequestMethod.GET, RequestMethod.POST })
	public void validateEmail(String email, HttpServletResponse resp,
			HttpServletRequest req) throws Exception {
		if (userService.getEmail(email)) {
			resp.getWriter().write("1");
		} else {
			resp.getWriter().write("0");
		}
	}

	/**
	 * 注册第一步完成，进入第二步
	 * 
	 * @return
	 */
	@RequestMapping(value = "/register/step2", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView step2(User user, String sq, Integer currentWeek,
			String sextemp, Date birthdaytemp, HttpServletResponse resp,
			HttpServletRequest req) throws Exception {

		if ("hyq".equals(sq)) {
			if (null == user.getBirthday() && null != currentWeek) {
				user.setBirthday(DateUtil.getDateByWeeks(currentWeek));
			}
		} else {
			if (null != birthdaytemp) {
				user.setBirthday(birthdaytemp);
			}
			if ("0".equals(sextemp)) {
				user.setSex(SexType.F);
			}
			if ("1".equals(sextemp)) {
				user.setSex(SexType.M);
			}
		}

		user.setPassword(StringUtil.string2MD5(user.getPassword()));
		user.setCreateDate(new Date());
		user.setName(user.getEmail());
		user.setLocked(Boolean.FALSE);
		user.setActive(Boolean.TRUE);

		try {
			userService.saveRegisterUser(user);
		} catch (Exception e) {
			logger.error("Register user step1 error.", e);
			return new ModelAndView("error");
		}

		// 设置用户已经登陆
		User uu = userService.getUserByEmail(user.getEmail());
//		User uu = userService.getUserByEmail("1111@qq.com");
		req.getSession(true).setAttribute(SESSION_USER_KEY, uu);

		Map<String, Object> map = new HashMap<String, Object>();

		// 官网正常注册购买的产品，网站正常销售
		List<Product> products = userService
				.getProductByType(ProductType.OfficialBase);

		List<ProductVO> vos = new ArrayList<ProductVO>();
		for (Product o : products) {
			ProductVO vo = new ProductVO();
			vo.setId(o.getId().toString());
			vo.setName(o.getName());
			vo.setDescription(o.getDescription());
			vo.setPrice(StringUtil.fenToYuan(o.getPrice()));
			vos.add(vo);
		}
		map.put("products", vos);
		map.put("email", uu.getEmail());
		this.setMenu(map, MENU_VALUE_REGISTER);

		return new ModelAndView("register/reg2", map);
	}

	/**
	 * 注册第二步完成，进入第三步
	 * 
	 * @return
	 */
	@RequestMapping(value = "/register/step3", method = { RequestMethod.GET,
			RequestMethod.POST })
	public ModelAndView step3(String email, HttpServletResponse resp,
			HttpServletRequest req) throws Exception {
		
		Map<String, Object> param = new HashMap<String, Object>();
		Order order = null;
		
		User user = (User)req.getSession(true).getAttribute(SESSION_USER_KEY);
		if(null == user){
			return new ModelAndView("error");
		}
		
		try{
			order = paymentService.getLastOrderByUserId(user.getId());
		}catch(Exception e){
			logger.error("Register step3 error.", e);
			return new ModelAndView("error");
		}
		
        param.put("order", order == null ? null : convertOrderVO(order));
		this.setMenu(param, MENU_VALUE_REGISTER);

		return new ModelAndView("register/reg3", param);
	}
	
	private OrderVO convertOrderVO(Order order){
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		
		OrderVO vo = new OrderVO();
		vo.setId(order.getId());
		vo.setAmount(StringUtil.fenToYuan(order.getAmount()));
		vo.setOrderDate(df.format(order.getOrderDate()));
		vo.setOrderNo(order.getOrderNo());
		vo.setOrderStatus(order.getOrderStatus() == null ? "&nbsp; " : order.getOrderStatus().toString());
		vo.setPaymentType(order.getPaymentType() == null ? " &nbsp;" : order.getPaymentType().toString());
	    vo.setOrderFrom(order.getOrderFrom() == null ? "&nbsp;" : order.getOrderFrom().toString());
	    
	    return vo;
	}

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(
				dateFormat, true));
	}

}
